package org.inspursc.s0517.health.evaluation.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import org.inspursc.s0517.health.common.entity.SysUser;
import org.inspursc.s0517.health.common.util.SpringSecurityUtils;
import org.inspursc.s0517.health.evaluation.converter.AnRadioConverter;
import org.inspursc.s0517.health.evaluation.converter.SurveyAnswerConverter;
import org.inspursc.s0517.health.evaluation.dao.SurveyAnswerDao;
import org.inspursc.s0517.health.evaluation.dto.*;
import org.inspursc.s0517.health.evaluation.entity.AnRadio;
import org.inspursc.s0517.health.evaluation.entity.SurveyAnswer;
import org.inspursc.s0517.health.evaluation.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.sql.Timestamp;
import java.text.Format;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author B_Dream
 * @date 2018/6/6 16:29
 */
@Service
public class SurveyAnswerServiceImpl implements SurveyAnswerService {

    @Autowired
    SurveyAnswerDao answerDao;

    @Autowired
    AnRadioService anRadioService;

    @Autowired
    CustomerService customerService;
    @Autowired
    QuestionCategoryService categoryService;


    /**
     * 提交问卷保存并计算结果
     * @param dto
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public SurveyAnswerGradeDTO saveAnswer(SurveyAnswerDTO dto, HttpServletRequest request) throws Exception {

        //获取当前用户信息
        SysUser user = SpringSecurityUtils.getCurrentUser(request);
        //评估师id
        Integer appraiserId = null;
        //组织机构id
        Integer organizationId = null;
        if (user != null) {
            appraiserId = user.getId();
            organizationId = user.getOrganizationId();
        }

        //判断回答数据是否被重复提交
        List<SurveyAnswer> surveyAnswers = answerDao.findAllByAppraiserIdAndAndDateTime(appraiserId, dto.getDateTime());
        if (surveyAnswers != null && surveyAnswers.size() > 0) {
            throw new Exception("导入数据异常！该问卷已被提交。");
        }

        //dto To entity
        SurveyAnswer surveyAnswer = SurveyAnswerConverter.converter(dto);
        surveyAnswer.setAppraiserId(appraiserId);
        surveyAnswer.setOrganizationId(organizationId);


        Integer personnelId = dto.getPersonnelId();
        CustomerDTO customer = customerService.findById(personnelId);

        Multimap<String, AnRadioDTO> anRadioMultimap = ArrayListMultimap.create();
        Set<Integer> cateIds = Sets.newHashSet();
        dto.getQuestions().forEach(e -> {
            String prStr = e.getPrimaryCategoryId() + "-" + e.getSecondCategoryId();
            cateIds.add(e.getPrimaryCategoryId());
            cateIds.add(e.getSecondCategoryId());
            anRadioMultimap.put(prStr, e);
        });
        //根据分类ID批量获取分类信息
        List<QuestionCategoryDTO> categoryDTOS = categoryService.findBatch(cateIds);

        Integer survey = dto.getSurveyId();
        surveyAnswer.setDateTime(dto.getDateTime());

        List<AnRadio> anRadios = new ArrayList<>();

        for (AnRadioDTO anRadioDTO : dto.getQuestions()) {
            AnRadio radio = AnRadioConverter.converter(anRadioDTO);
            radio.setDateTime(dto.getDateTime());
            radio.setAppraiserId(appraiserId);
            radio.setPersonnelId(personnelId);
            radio.setOrganizationId(organizationId);
            radio.setSurveyId(survey);
            anRadios.add(radio);
        }


        //问卷分析方法
//        Map<String, Object> map = AppraiseFactoryService
//                .getAppraise(AppraiseFactoryService.ONE_SURVEY)
//                .appraise(anRadioMultimap, customer, categoryDTOS);

        //To survey anlyse function changed by zcl 2018-09-10
        Map<String, Object> map = AppraiseFactoryService
                .getAppraise(dto.getSurveyId())
                .appraise(anRadioMultimap, customer, categoryDTOS);

        surveyAnswer.setTotalScore((int)map.get("total_score"));
        surveyAnswer.setDescription((String) map.get("description"));
        JSON antoMap=(JSON) map.get("anto_map");
        String antoStr=JSONObject.toJSONString(antoMap);
        surveyAnswer.setAntoComputeJson(antoStr);

        String kpiStr = JSONObject.toJSONString(map);

        surveyAnswer.setKpi(kpiStr);

        if (surveyAnswer.getTotalScore() > 10) {
            surveyAnswer.setSuggestion("此时评估结果为正常 测试文本返回");
        } else {
            surveyAnswer.setSuggestion("此时评估结构为异常，测试结果返回");
        }
        SurveyAnswer answer = answerDao.save(surveyAnswer);
        SurveyAnswerGradeDTO answerDTO;
        answerDTO = SurveyAnswerConverter.converterToGrade(answer);
        answerDTO.setKpi(map);
        for (AnRadio anRadio : anRadios) {
            anRadio.setHealthResultId(answer.getId());
        }

        anRadioService.saveBatchAnRadio(anRadios);

        return answerDTO;

    }


    @Override
    public SurveyAnswerDTO findOneBySuAndPer(Integer suId, Integer perId) {
        SurveyAnswer answer = answerDao.findBySurveyIdAndAndPersonnelId(suId, perId);

        if (answer != null) {
            List<AnRadioDTO> anRadio = anRadioService.findAnRadio(answer.getSurveyId(), answer.getPersonnelId());
            SurveyAnswerDTO dto = SurveyAnswerConverter.converter(answer);
            dto.setQuestions(anRadio);
            return dto;
        } else {
            return null;
        }
    }

    @Override
    public SurveyAnswerGradeDTO findOneById(Integer id) {

        SurveyAnswer answer = answerDao.getOne(id);
        String kpi = answer.getKpi();
        JSONObject jsonObject = JSON.parseObject(kpi);
        SurveyAnswerGradeDTO dto = new SurveyAnswerGradeDTO();
        BeanUtils.copyProperties(answer, dto);
        dto.setKpi(jsonObject);
        return dto;
    }

    @Override
    public List<SurveyAnswerDTO> findAllByPersonnel(Integer id) {

        List<SurveyAnswer> answers = answerDao.findAllByAndPersonnelId(id);
        List<SurveyAnswerDTO> dtos = answers.stream().map(SurveyAnswerConverter::converter).collect(Collectors.toList());
        return dtos;
    }

    @Override
    public SurveyAnswerDateDTO getAnswerDetailById(Integer id, HttpServletRequest request) {
        SurveyAnswer answers = answerDao.getOne(id);

        SurveyAnswerDateDTO answerDTO = SurveyAnswerConverter.converterDateStr(answers);
        answerDTO.setDateTime(this.getNowDateShort(answers.getDateTime()));
        List<AnRadioDTO> radioDTOS = anRadioService.findAllBySuAnswerId(answers.getId());
        answerDTO.setQuestions(radioDTOS);

        return answerDTO;
    }

    @Override
    @Transactional
    public boolean deleteAnswerById(Integer id) {
        try {
            anRadioService.deleteByHealthResultId(id);
            answerDao.deleteById(id);
            return true;
        }catch (Exception e) {
            throw e;
        }
    }

    private String getNowDateShort(Date dateTime) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(dateTime);
        return dateString;
    }

}
